import time, hashlib
from flask_restful import request
from init import redis_store


def token_md5(password):
    p_str_1 = 'taojiji'
    p_str_2 = 'shandian@taojiji'
    ctime = str(time.time())
    m = hashlib.md5(bytes(password + p_str_1 + ctime, encoding='utf-8'))
    m.update(bytes(p_str_2, encoding='utf-8'))
    return m.hexdigest()


def verify_token(function):
    # HTTP_AUTHORIZATION
    auth_erre = {'message': 'auth fail,please check the auth message(token&user_id)'}

    def verfiy_api(*args, **kwargs):
        token_userid = request.headers.get('auth')
        token_userid_arr = str(token_userid).split(',')
        if len(token_userid_arr) < 2:
            return auth_erre, 401
        token = token_userid_arr[0]
        user_id = token_userid_arr[1]
        token_redis = redis_store.hget('platformLogin', user_id)
        if token_redis and str(token_redis, 'utf-8') == token:
            return function(*args, **kwargs)
        else:
            return auth_erre, 401

    return verfiy_api



def get_token():
    return str(request.headers.get('auth')).split(',')[0]
